<template>
    <a-list size="small" bordered :data-source="dataSource">
        <template #header>
            <a @click="onAdd">新增</a>
        </template>
        <template #renderItem="{ item, index }">
            <a-list-item>
                <a-input v-model:value="item.editValue" v-if="item.editing"> </a-input>
                <span v-else>{{ item.value }}</span>
                <template #actions>
                    <template v-if="item.editing">
                        <a @click="onEdit(index, item)">保存</a>
                        <a style="color: red" @click="onCancel(item)">取消</a>
                    </template>
                    <template v-else>
                        <a @click="Editing(item)">编辑</a>
                        <a-popconfirm title="Sure to delete?" @confirm="onDel(index)">
                            <a style="color: red">删除</a>
                        </a-popconfirm>
                    </template>
                </template>
            </a-list-item>
        </template>
    </a-list>
</template>
<script lang="ts">
import { defineComponent, nextTick, reactive, toRefs, watch } from 'vue'

interface dataSourceItem {
    editValue: string
    editing: boolean
    value: string
}

export default defineComponent({
    name: 'ListComp',
    emits: ['onDel', 'onEdit', 'onAdd'],
    props: {
        list: {
            type: Array,
            default: () => []
        },
        dataKey: {
            type: String,
            default: () => ''
        }
    },
    setup(props, { emit }) {
        const state = reactive({
            dataSource: [] as dataSourceItem[]
        })
        watch(
            () => props.list,
            () => {
                state.dataSource = props.list.map((el: any) => {
                    return {
                        editValue: el,
                        editing: false,
                        value: el
                    }
                })
            },
            { immediate: true }
        )
        const methods = {
            onAdd() {
                emit('onAdd', { key: props.dataKey })
            },
            onDel(index: number) {
                emit('onDel', { key: props.dataKey, index })
            },
            Editing(item: dataSourceItem) {
                item.editing = true
            },
            onEdit(index: number, item: dataSourceItem) {
                emit('onEdit', {
                    key: props.dataKey,
                    index,
                    value: item.editValue
                })
                nextTick(() => {
                    item.editing = false
                })
            },
            onCancel(item: dataSourceItem) {
                item.editing = false
                item.editValue = item.value
            }
        }
        return {
            ...toRefs(state),
            ...methods
        }
    }
})
</script>
